package com.hmyd.hmyd_android.shop;

import java.lang.reflect.Type;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.common.base.Objects;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.DtoInfoNoPage;
import com.hmyd.hmyd_android.dto.ShopDetailImage;
import com.hmyd.hmyd_android.fragment.BasicFragment;
import com.hmyd.hmyd_android.view.MySnapPageLayout;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapCommonUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 商品图片详情
 * @author wangk
 * 
 */
public class GoodsDetailFragment extends BasicFragment {
	
	private static final int GET_GOOD_IMAGES = 1031;
	
	private ScrollView rootView;
	private MySnapPageLayout mcoySnapPageLayout;
	private ScrollView mScrollView;
	private LinearLayout ll_items;
	
	private String id;
	
	private boolean isPrepared;		// 是否初始化完成
	private boolean isVisible;		// 是否可见  

	public GoodsDetailFragment(){}
	
	
	public void setArguments(MySnapPageLayout mcoySnapPageLayout, String id){
		this.mcoySnapPageLayout = mcoySnapPageLayout;
		this.id = id;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater,  ViewGroup container,
			 Bundle savedInstanceState) {
		rootView = (ScrollView) inflater.inflate(R.layout.fragment_goods_details, null);
		
		isPrepared = true;
		lazyLoad();
		
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		/*if (isVisibleToUser) {
			// 相当于Fragment的onResume
			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", id);
//			onRequest(1, UrlConstant.GOODSDETIALS_IMAGE, HttpMethod.GET, params);
		} else {
			// 相当于Fragment的onPause
		}*/
		
		if(getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
	}
	
	protected void onVisible(){
		lazyLoad();
	}

	/**
	 * 防止Fragment每次加载初始化控件
	 */
	protected void lazyLoad(){
		if(!isPrepared || !isVisible) {
            return;
        }
		
		mScrollView = (ScrollView) rootView.findViewById(R.id.my_scroll_view);
		mScrollView.setOnTouchListener(new TouchListenerImpl());

		ll_items = (LinearLayout) rootView.findViewById(R.id.first_column);
		if(!Objects.equal(null, id)) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", id);
			onRequest(GET_GOOD_IMAGES, UrlConstant.GOODSDETIALS_IMAGE, HttpMethod.GET, params);
		}
	}

	protected void onInvisible(){}

	@Override
	public void onPostSuccess(int postId, String msg) {
		Gson gson = new Gson();
		switch (postId) {
		case GET_GOOD_IMAGES:
			DtoInfoNoPage<List<ShopDetailImage>> dtoInfoNoPage = new DtoInfoNoPage<List<ShopDetailImage>>();
			Type type1 = new TypeToken<DtoInfoNoPage<List<ShopDetailImage>> >() {
			}.getType();
			dtoInfoNoPage = gson.fromJson(msg, type1);
			List<ShopDetailImage> datas = dtoInfoNoPage.data;
			if(!Objects.equal(null, datas) && datas.size()>0) {
				addImageView(datas);
			} else {
				final Dialog progressDialog = new Dialog(getActivity(),R.style.progress_dialog);
				progressDialog.setContentView(R.layout.view_toast);
				progressDialog.setCancelable(true);
				progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
				ImageView imageError = (ImageView) progressDialog.findViewById(R.id.icon);
				imageError.setImageResource(R.drawable.ji_icon_shan);
				TextView msgtv = (TextView) progressDialog.findViewById(R.id.msg);
				msgtv.setTextSize(12);
				msgtv.setText("网络异常");
				progressDialog.show();
				Log.e("goodDetail-Image", "获取图片失败");
			}
			break;
		default:
			break;
		}
		
	}
	
	private void addImageView(List<ShopDetailImage> datas){
		BitmapUtils bitmapUtils;
		if(getActivity() != null) {
			bitmapUtils = new BitmapUtils(getActivity());
		} else {
			return;
		}
		
		BitmapDisplayConfig displayConfig = new BitmapDisplayConfig();
		displayConfig.setLoadFailedDrawable(getResources().getDrawable(R.drawable.view_no_photo));
		displayConfig.setLoadingDrawable(getResources().getDrawable(R.drawable.view_no_photo));
		displayConfig.setShowOriginal(false);
		displayConfig.setBitmapMaxSize(BitmapCommonUtils.getScreenSize(getActivity()));
		
		for (int i = 0; i < datas.size(); i++) {
			ImageView imageView = new ImageView(getActivity());
			imageView.setScaleType(ScaleType.FIT_XY);
			imageView.setPadding(5, 5, 5, 5);
			imageView.setAdjustViewBounds(true);
			
			Bitmap bmp = bitmapUtils.getBitmapFromMemCache(datas.get(i).images, displayConfig);
			
			if (bmp != null) {
				imageView.setImageBitmap(bmp);
			} else {
				bitmapUtils.display(imageView, datas.get(i).images, displayConfig);
			}
			
			ll_items.addView(imageView);
		}
		
	}

	private class TouchListenerImpl implements OnTouchListener {
		@SuppressLint("ClickableViewAccessibility")
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:
				int scrollY1 = view.getScrollY();
				if (scrollY1 == 0) {
					Intent intent = new Intent("isTop");
					intent.putExtra("isTop", "isTop");
					getActivity().sendBroadcast(intent);
				} else {
					Intent intent = new Intent("isTop");
					intent.putExtra("isTop", "notTop");
					getActivity().sendBroadcast(intent);
				}

				break;
			case MotionEvent.ACTION_MOVE:
				int scrollY = view.getScrollY();
				int height = view.getHeight();
				int scrollViewMeasuredHeight = rootView.getChildAt(0).getMeasuredHeight();
				if (scrollY == 0) {
					Intent intent = new Intent("isTop");
					intent.putExtra("isTop", "isTop");
					getActivity().sendBroadcast(intent);
				} else {
					Intent intent = new Intent("isTop");
					intent.putExtra("isTop", "notTop");
					getActivity().sendBroadcast(intent);
				}
				if ((scrollY + height) == scrollViewMeasuredHeight) {
					Intent intent = new Intent("loadMore");
					getActivity().sendBroadcast(intent);
				}
				break;

			default:
				break;
			}
			return false;
		}

	};

	@Override
	public void onDestroy() {
		getActivity().unregisterReceiver(mcoySnapPageLayout.broadcastReceiver);
		super.onDestroy();
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		// TODO Auto-generated method stub
		
	}

}
